from sqlalchemy import select, desc
import typing as T

from ...init.Database import getSession, AsyncSession
from ...pojo import UserChatHistory, UserChatHistoryVO


class _UserChatHistoryMapper:
    session: AsyncSession = None
    generator: T.AsyncGenerator = None

    async def __aenter__(self):
        self.generator = getSession()
        self.session = await anext(self.generator)

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        try:
            if not exc_type:  # 无异常时提交
                await self.session.commit()
            else:
                await self.session.rollback()  # 异常时回滚
            await self.generator.aclose()  # 关闭生成器
        except Exception as e:
            await self.session.rollback()  # 强制回滚异常
        finally:
            self.generator = None
            self.session = None

    async def getBySessionId(self, sessionId: int, limit: int = 10):
        async with self:
            result = (
                (
                    await self.session.execute(
                        select(UserChatHistory)
                        .where(UserChatHistory.sessionId == sessionId)
                        .order_by(desc(UserChatHistory.id))
                        .limit(limit)
                    )
                )
                .scalars()
                .all()
            )

            return [UserChatHistory(**item.model_dump()) for item in result]

    async def insertBatch(self, data: list[UserChatHistory]):
        async with self:
            self.session.add_all(data)


_userChatHistoryMapper: _UserChatHistoryMapper = _UserChatHistoryMapper()
